package cn.xmoit.service.impl;

import cn.xmoit.observer.OrderObserver;
import cn.xmoit.message.PlaceOrderMessage;
import cn.xmoit.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author fangyy
 */
@Service("orderService2")
@Slf4j
public class OrderServiceImpl implements OrderService {

	/**
	 * 实现类里也要注入一下
	 */
	@Autowired
	private List<OrderObserver> orderObserverList;

	/**
	 * 定义一个线程池,这里参数随便写的
	 */
	ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(6, 12, 6, TimeUnit.SECONDS,
			new ArrayBlockingQueue<>(30));

	/**
	 * 通知所有观察者
	 * @param placeOrderMessage 通知消息
	 */
	public void notifyObservers(PlaceOrderMessage placeOrderMessage) {
		for (OrderObserver orderObserver : orderObserverList) {
			// 利用多线程异步执行
			threadPoolExecutor.execute(() -> orderObserver.afterPlaceOrder(placeOrderMessage));
		}
	}

	/**
	 * 下单
	 */
	@Override
	public void placeOrder() {
		log.info("[placeOrder] start.");
		// 通知观察者
		this.notifyObservers(new PlaceOrderMessage());
		log.info("[placeOrder] end.");
	}

}
